<?php

namespace Utuo;

use Utuo\WechatAdvance;
use Think\Controller;
use My\Model\WechatUserModel;

class MallForeground extends Controller {
	
	/**
	 * 每页显示条数
	 *
	 * @var int
	 */
	protected $pageSize = 10;
	
	/**
	 * 跳转状态码
	 * @var unknown
	 */
	const STATE_CODE = 'utuo';
	
	/**
	 * 登录接口
	 * @var object
	 * @see \Utuo\WechatUserLogin
	 */
	protected $login = null;
	
	/**
	 * 高级接口
	 * @var unknown
	 */
	protected $wechatAdvance = null;
	
	/**
	 * 微信id
	 * @var unknown
	 */
	protected $openId = 0;
	
	/**
	 *  客户id
	 * @var unknown
	 */
	protected $cid = 0;
	
	/**
	 * 用户id
	 * @var unknown
	 */
	protected $uid = 0;
	
	/**
	 * 是否检查登录
	 * @var unknown
	 */
	protected $checkLogin = true;
	
	/**
	 * 是否支持跳转
	 * @var unknown
	 */
	protected $supportRedirect = false;
	
	/**
	 * 网站信息
	 * @var array
	 */
	protected $config = array ();
	
	/**
	 * 微信设置
	 * @var array
	 */
	protected $wechatConfig = array();
	
	/**
	 * 网站主题信息
	 * @var array
	 */
	protected $theme = array ();
	
	/**
	 * 模型名称
	 * @var unknown
	 */
	protected $modelName = "";
	
	/**
	 * 模型控制器名称
	 * @var unknown
	 */
	protected $modelControllerName = "";
	
	/**
	 * 分享数据
	 * @var unknown
	 */
	protected $share = array();
	
	/**
	 * 页面标题
	 * @var string
	 */
	private $pageTitle = '';
	
	/**
	 * 获得当前页码
	 *
	 * @return int
	 */
	protected function getPage() {
		return I('p', 1, 'intval');
	}
	
	/**
	 * 获取分页大小
	 *
	 * @return number
	 */
	protected function getPageSize() {
		$this->pageSize = I('pageSize', 10, 'intval');
		return $this->pageSize;
	}
	
	
	/**
	 * 设置是否支持分享
	 * @param unknown $shareEnabled
	 */
	protected function setShareEnabled($shareEnabled) {
		$this->shareEnabled = $shareEnabled;
	}
	
	/**
	 * 设置是否支持跳转
	 * @param unknown $supportRedirect
	 */
	protected function setSupportRedirect($supportRedirect) {
		$this->supportRedirect = $supportRedirect;
	}
	
	/**
	 * 设置是否检查登录
	 * @param unknown $checkLogin
	 */
	protected function setCheckLogin($checkLogin) {
		$this->checkLogin = $checkLogin;
	}
	
	/**
	 * 设置模型
	 * 
	 * @param string $name
	 */
	protected function setModelName($name = null) {
		$name or $name = CONTROLLER_NAME;
		$this->modelName = $name;
	}
	
	/**
	 * 设置模型控制器名
	 * 
	 * @param string $name
	 */
	protected function setModelControllerName($name = null) {
		$name or $name = CONTROLLER_NAME;
		$this->modelControllerName = $name;
	}
	
	/**
	 * 设置页面标题
	 *
	 * @param string $pageTitle
	 */
	public function setPageTitle($pageTitle, $suffix = null) {
		$this->pageTitle = $pageTitle;
		empty($suffix) or $this->pageTitle .= ' - ' . $suffix;
		return $this;
	}
	
	/**
	 * 设置分享内容
	 * @param unknown $config
	 * array(
	 * 	  'imgUrl' => '',
	 * 	  'link' => '',
	 *    'desc' => '',
	 *    'title' => '',
	 * )
	 */
	public function setShare( $config ) {
		$this->share = array_merge( $this->share, $config );
	} 
	
	protected function appExit($msg){
	    header("Content-Type: text/html; charset=UTF-8");
	    die($msg);
	}
	
	/**
	 * 重构display
	 * 
	 * @see \Think\Controller::display()
	 */
	protected function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
		C('TMPL_PARSE_STRING.__DEFAULT__', __ROOT__ . '/Public/Style/' . MODULE_NAME . '/Default');
		C('TMPL_PARSE_STRING.__COMMON__', __ROOT__ . '/Public/Style/Common');
		// layout(false);
		C('TMPL_PARSE_STRING.__TITLE__', $this->pageTitle ?  : $this->config['name']);
		
		/* 分享 */
		$this->share['title'] or $this->share['title'] = C('TMPL_PARSE_STRING.__TITLE__');
		$this->share['imgUrl'] or $this->share['imgUrl'] = $this->user['face'] ? $this->user['face'] : $this->config['logo'] ? $this->config['logo'] : '';
		$this->share['link'] or $this->share['link'] = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'].(($_SERVER['SERVER_PORT'] == 80 || $_SERVER['SERVER_PORT'] == 443) ? '' : ':'.$_SERVER['SERVER_PORT']).$_SERVER['REQUEST_URI'];
		$this->share['desc'] or $this->share['desc'] = $this->config['description'];
		$this->share = array_filter($this->share);
		$this->assign("share", empty($this->share) ? "{}" : json_encode($this->share) );
		
		/* WECHAT JSAPI 签名包 */
		$signPackage = $this->wechatAdvance->getSignPackage();
		$this->assign("wxConfig", $signPackage);
		
		parent::display($templateFile, $charset, $contentType, $content, $prefix);
	}
	
	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct();
		$this->tid = I("get.tid", 0, "intval") or $this->tid = I("post.tid", 0, "intval");
		$this->cid = I('get.sid', 0, 'intval') or $this->cid = I("post.sid", 0, "intval");
		$this->sid = $this->cid;
		if (!$this->cid) {
			$this->cid = C('DEFAULT_SITE_ID');
		}
		$this->assign("sid", $this->sid);
		
		// 设置openId
		$this->openIdKey = "openId{$this->cid}";
		session("openIdKey", $this->openIdKey);
		$this->setOpenId(); // 把session中的openId设置为当前
		
		// 微信设置
		$this->wechatConfig = $wechat = M("Wechat")->where('cid=%d', $this->cid)->find();
		$this->wechatAdvance = new WechatAdvance($wechat['appid'], $wechat['appsecret']);
		if (empty($wechat['appid']) or empty($wechat['appsecret'])) {
			$this->responseMsg('请设置微信开发者配置信息');
		}
		
		// 设置登录接口
		$this->login = WechatUserLogin::newInstance(array(
			'cid' => $this->cid,
			'wechatAdvance' => $this->wechatAdvance,
		));
		$this->user = $this->login->getLogin();
		$this->uid = $this->user['id'];
		
		// 调试时模似登录
		if ( isset( $_REQUEST['debug'] ) and $_REQUEST['debug'] == 'zhangrui.songyi') {
			$user = $this->login->getLogin();
			$debugUid = $_REQUEST['debugUid'] or $debugUid = 29;
			if (!$user or !$user['id']) {
				$vuser = M("WechatUser")->where('cid=%d and id=%d', $this->cid, $debugUid)->find();
				$this->login->setLogin($vuser);
			}
		}
		
		method_exists($this, '_init') && $this->_init();
		
		/* 推广处理 */
		if ( IS_AJAX ) {
			layout(false);
			$this->setSupportRedirect(false);
		}
		// 支持跳转获得用户信息并登录
		if ( $this->supportRedirect ) {
			$this->promotionEnter();
		}
		// 检查登录
		if ( $this->requireLogin() and !$this->login->checkLogin() ) {
			if (IS_AJAX) {
				$this->ajaxError("还未登录,请重新打开首页系统将自动完成登录.");
			} else {
				/* 刷新用户信息 */
				$user = $this->login->refreshWechatUser();
				$this->login->setLogin($user);
				if ( !$this->login->checkLogin() ) {
					$this->responseMsg('您的微信账号未能成功登录系统');
				}
			}
		}
		
		// 分享人信息
		$fromUser = M("WechatUser")->where(array (
				'cid' => $this->cid,
				'id' => $this->user['mid'],
		))->find();
		$this->assign('fromUser', $fromUser);
		// 登录用户
		$assignUser = $this->user;
		$assignUser and $assignUser['subscribe'] = ($assignUser['subscribe']*1 ? 1 : 0);
		$assignUser and $assignUser["typeName"] = WechatUserModel::getUserTypeName($assignUser['type'], $assignUser['uid']);
		$this->assign('user', $assignUser);
		
		/* 主题设置 */
		$modelName = $this->modelName;
		$themeStyle = 'Default';
		$themeTemplate = 'Default';
		if ($modelName) {
			$config = $this->getModelConfig();
			if ($config['status'] != 1)
				$this->responseMsg("网站已关闭");
			$this->tid === 0 and $this->tid = $config['theme'];
			$themeConfig = $this->getThemeConfig($this->tid, $config);
			$this->assign('style', $themeConfig);
			$config['url'] = url('Home', $this->modelControllerName ? $this->modelControllerName : $modelName, '', array (
					'sid' => $this->sid 
			));
			$this->config = $config;
			$this->assign("config", $config);
			$this->assign(lcfirst($modelName), $config);
			if (!empty($this->tid)) {
				$theme = M("Theme")->find($this->tid);
				$themeStyle = $theme['style'];
				$themeTemplate = $theme['template'];
			}
		}
		$this->assign('system', M('system')->find());
		$this->assign('path', CONTROLLER_NAME.'/'.ACTION_NAME);
		C('TMPL_PARSE_STRING.__STYLE__', __ROOT__ . '/Public/Style/' . MODULE_NAME . '/' . $themeStyle);

		parent::theme($themeTemplate);
		
		C('TMPL_ACTION_ERROR', './error'); // 默认错误跳转对应的模板文件
		C('TMPL_ACTION_SUCCESS', './success'); // 默认成功跳转对应的模板文件
		
// 		// 记录客户PV
// 		PVReport::report($this->cid);
// 		\Utuo\UtuoLog::doLogPost("WmflFront", array(
// 			'user' => session($this->sessionKey),
// 		));
	}
	
	/**
	 * 登录相关SESSION名
	 * 
	 * @var array
	 */
	private $sessionKeys = array ();
	
	/**
	 * 当前session中的用户信息
	 * 
	 * @var unknown
	 */
	protected $user = null;
	
	/**
	 * 获得主题配置
	 * 
	 * @param $tid 选择的主题
	 * @return $config 当前的主题设置
	 */
	private function getThemeConfig($tid, $config) {
		$themeConfig = M("ThemeConfig")->where("cid=%d and theme=%d", $this->cid, $tid)->getField("config");
		$themeConfig = unserialize($themeConfig);
		return $themeConfig;
	}
	
	
	/**
	 * 获得渠道id
	 * @return Ambigous <mixed, void, NULL, multitype:, unknown, string>
	 */
	protected function getQid() {
		$qid = $this->qid or $qid = I('request.qid', 0, "intval") or $qid = cookie('_qid_'.$this->cid)*1;
		return $qid;
	}
	
	/**
	 * 设置渠道id
	 * @param unknown $aid
	 */
	protected function setQid( $qid ) {
		$this->qid = $qid*1;
		cookie('_qid_'.$this->cid, $qid ? $qid : null);
	}
	
	
	/**
	 * 获得代理商id
	 * @return Ambigous <mixed, void, NULL, multitype:, unknown, string>
	 */
	protected function getAid() {
		$aid = I('aid', 0) or $aid = cookie('aid')*1; // 代理模式加入
		if ( !($aid and $this->checkAid($aid)) ) {
			$aid = 0;
			cookie('aid', null);
		}
		return $aid;
	}
	
	/**
	 * 设置代理商id
	 * @param unknown $aid
	 */
	protected function setAid( $aid ) {
		cookie("aid", $aid ? $aid : null);
	}
	
	
	
	/**
	 * 推广进入(当需要跳转时调用此方法)
	 * @return
	 */
	public function promotionEnter() {
		$state = I('state', 0);
		$mid = I('mid', 0);
		$aid = $this->getAid(); // 代理模式加入
		$openId = 0;
		if ( !$this->requireLogin() or $this->login->checkLogin() ) {
			// 更改为可分享的地址
			if ( $this->uid and $mid != $this->uid or isset($_GET['state']) or isset($_GET['code']) ) {
				$redirectParam = array (
					'mid' => $this->uid, // 所有链接必须携带mid
				);
				$aid and $redirectParam['aid'] = $aid;
				$url = $this->getRedirectUrl( $redirectParam );
				redirect( $url );
			}
			$this->setAid($aid);
		} elseif ($state === self::STATE_CODE) { // 第一次推广进入
			$code = I("code", 0);
			$authAccessRes = $this->wechatAdvance->getAuthAccessToken($code);
			if ( $authAccessRes != false ) {
				$openId = $authAccessRes['openid'];
				if ( $openId ) {
					$this->setOpenId( $openId );
					// 初始微信用户信息绑定
					$user = $this->login->bindUser(array(
						'mid' => $mid,
						'cid' => $this->cid,
						'openId' => $openId,
					));
					$this->login->setLogin($user);
					// 刷新用户信息(针对关注后)
					$user = $this->login->refreshWechatUser($openId, $user);
					if ($user and $user['isFresh']) {
						$this->login->setLogin($user);
					}
					// 获得当前用户 的代理商id(代理模式下处理)
					if ( $user['type'] == WechatUserModel::USER_TYPE_AGENT ) {
						$aid = M("MallAgent")->where(array('wechat_uid' => $user['id']))->getField("id");
					}
					// 更改为可分享的地址
					if ($this->uid and $mid != $this->uid or isset($_GET['state']) or isset($_GET['code'])) {
						$redirectParam = array (
							'mid' => $this->uid,
						);
						$aid and $redirectParam['aid'] = $aid;
						$redirectUrl = $this->getRedirectUrl( $redirectParam );
						redirect($redirectUrl);
					}
				}
			} else {
				$this->responseMsg("error:".$this->wechatAdvance->getError());
			}
		} else {
			$redirectUrl = $this->wechatAdvance->getAuthRedirectUrl($this->getRedirectUrl(), 0, self::STATE_CODE);
			redirect($redirectUrl);
		}
	}
	
	/**
	 * 检测是否需要登录
	 * 
	 * @return boolean
	 */
	protected function requireLogin() {
		$user = session($this->sessionKey);
		if ( $user['debug'] or $_REQUEST['debug'] === 'zhangrui.songyi' ) { // 调试模式下session无有效期
			return false;
		}
		return $this->checkLogin;
	}
		
	/**
	 * AJAX返回正确信息
	 *
	 * @param string $msg
	 * @param array $extra
	 * @return
	 *
	 */
	protected function ajaxSuccess($msg = '操作成功', $extra = null, $redirectUrl = null, $redirectDelay = 1) {
		$data['error'] = 0;
		$data['msg'] = $msg;
		is_null($extra) or $data['extra'] = $extra;
		is_null($redirectUrl) or $data['redirect'] = array (
				'url' => $redirectUrl,
				'delay' => $redirectDelay * 1000 
		);
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($data));
	}
	
	/**
	 * AJAX返回错误信息
	 *
	 * @param string $msg
	 * @param array $extra
	 * @return \Utuo\BackgroundController
	 */
	protected function ajaxError($msg = '操作失败', $extra = null, $redirectUrl = null, $redirectDelay = 1) {
		$data['error'] = 1;
		$data['msg'] = $msg;
		is_null($extra) or $data['extra'] = $extra;
		is_null($redirectUrl) or $data['redirect'] = array(
		'url' => $redirectUrl,
		'delay' => $redirectDelay * 1000
		);
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($data));
	}
	
	/**
	 * 获取表单选择列表
	 *
	 * @param array $options
	 * @param string $default
	 * @param string $firstOption
	 * @return string
	 */
	protected function getOption($options, $default = null, $firstOption = null) {
		empty($options) && $options = array ();
		$ret = array ();
		empty($firstOption) or $ret[] = "<option value=''>$firstOption</option>";
		foreach ($options as $k => $v) {
			$selected = !is_null($default) && $default == $k ? " selected='selected'" : '';
			$ret[] = "<option value='$k'$selected>$v</option>";
		}
		return implode("\n", $ret);
	}
	
	/**
	 * 读写分离开关
	 * @param unknown $status
	 */
	protected function rwSeparate( $status ) {
		static $rwStatus = array();
		if ( $status ) {
			$rwStatus[] = 1;
			C('DB_HOST', SAE_MYSQL_HOST_M.','.SAE_MYSQL_HOST_S);
		} else {
			$last2 = $rwStatus[count($rwStatus)-2];
			if ( !$last2 ) {
				C('DB_HOST', SAE_MYSQL_HOST_M);
			}
			array_pop($rwStatus);
		}
	}
	
	/**
	 * 当前地址
	 * @param array $param 增加的参数
	 */
	protected function getCurrentUrl( $attach = array() ) {
		unset($_REQUEST[C('TOKEN_NAME')]);
		function toArray($data, $level, $path, &$result) {
			foreach ($data as $k => $v) {
				$p = $path . ($level ? "[" . $k . "]" : $k);
				if (is_array($v)) {
					toArray($v, 1 + $level, $p, $result);
				} else {
					$result[$p] = $v;
				}
			}
			return $result;
		}
		$soure = array ();
		$attach and $soure = array_merge($soure, $attach);
		$result = toArray($_REQUEST, 0, "", $soure);
		$queryString = "";
		foreach ($result as $k => $v)
			$queryString .= $k . "=" . $v . "&";
		$queryString = trim($queryString, "&");
		return url(null, CONTROLLER_NAME, ACTION_NAME, "") . "?" . $queryString;
	}
	
	/**
	 * 响应消息
	 * @param unknown $msg
	 */
	protected function responseMsg( $msg, $error = 1, $wparam = array() ) {
		$fun = "";
		if ( IS_AJAX ) {
			$fun = $error ? "ajaxError" : "ajaxSuccess";
			$this->$fun ( $msg, $wparam );
		} else {
			$fun = $error ? "error" : "success";
			$this->$fun( $msg );
		}
	}
	
	/**
	 * 获得模型配置信息
	 */
	private function getModelConfig() {
		$config = M($this->modelName)->where("cid=%d", $this->sid)->find();
		$configArray = unserialize($config['config']);
		$config['config'] = array ();
		foreach ($configArray as $k => $v) {
			$config['config'][$v['name']] = $v['value'];
		}
		if (empty($config['config']))
			unset($config['config']);
		return $config;
	}
	
	/**
	 * 当前URL
	 * 
	 * @param 附加参数
	 */
	private function getRedirectUrl($wparam) {
		$queryString = $_SERVER['QUERY_STRING'];
		if ($wparam) {
			$params = array ();
			parse_str($queryString, $params);
			$params = array_merge($params, $_GET); // 加入pathinfo url中的参数
			foreach ($wparam as $k => $v) {
				$params[$k] = $v;
			}
			unset($params['state']);
			unset($params['code']);
			$paramsTmp = array ();
			foreach ($params as $k => $v) {
				$paramsTmp[] = $k . "=" . $v;
			}
			$queryString = join('&', $paramsTmp);
		}
		$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . (!empty($queryString) ? '?' . $queryString : '');
		return $url;
	}
	
	/**
	 * 设置微信id
	 * @param $openId 要设置的微信号(不传将从request与session中获取)
	 */
	private function setOpenId( $openId = 0 ) {
		$this->openId = $openId ? $openId : 0; // I('request.open_id', 0)
		$sessionOpenid = session($this->openIdKey);
		if ( $this->openId ) {
			session($this->openIdKey, $this->openId);
		} else {
			$this->openId = $sessionOpenid ? $sessionOpenid : 0;
		}
		$this->assign("openId", $this->openId);
	}
	
	/**
	 * 验证代理商
	 */
	private function checkAid( $aid ) {
		return M("MallAgent")->where('cid=%d and id=%d', $this->cid, $aid)->count() ? true : false;
	}
}
